package com.iceland.client.client.proxy;


import com.iceland.common.message.CmdMessage;
import com.iceland.common.message.DataType;
import com.iceland.common.message.MessageType;
import com.iceland.common.util.AttributeKeyUtils;
import com.iceland.common.util.ChannelContext;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 转发收到的数据给客户端
 */
@Slf4j
public class ProxyHandler extends ChannelInboundHandlerAdapter {

    //缓存的数组
//    ByteBuf writeBuffer= PooledByteBufAllocator.DEFAULT.buffer();

    //连接
    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        //1.加入到可用列表中
//        log.info("真实服务器通道，l:{},r:{}",ctx.channel().localAddress(),ctx.channel().remoteAddress());
        ctx.fireChannelRegistered();
    }
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //1.加入到可用列表中
        log.info("真实服务器通道，l:{},r:{}",ctx.channel().localAddress(),ctx.channel().remoteAddress());
        ctx.fireChannelActive();
    }


    //读取
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        ChannelContext channelContext = AttributeKeyUtils.getChannelContext(ctx.channel());
        ByteBuf in=(ByteBuf)msg;
        int readableBytes=in.readableBytes();
        if(in.readableBytes()>0){

            CmdMessage cmdMessage=new CmdMessage(MessageType.DATA_EXCHANGE.getType(),null,in);
            Channel bindChannel = channelContext.getBindChannel();
            bindChannel.writeAndFlush(cmdMessage);
            log.debug("转发流量{}：代理客户端{}接收到消息，通过{}转发消息至CMD服务端{}",readableBytes,ctx.channel().localAddress(),bindChannel.localAddress(),bindChannel.remoteAddress());

        }

    }

    //断开
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        ChannelContext channelContext = AttributeKeyUtils.getChannelContext(ctx.channel());
        log.info("通道关闭，l:{},r：{}",ctx.channel().localAddress(),ctx.channel().remoteAddress());
        if(channelContext!=null){
            //释放代理通道
            Channel bindChannel = channelContext.getBindChannel();
            if(bindChannel!=null){
                bindChannel.close();
            }
        }
        ctx.fireChannelInactive();
    }
}
